#-*- co utf-8 -*-
import sys, glob, json, traceback

from Crypto import Random
from Crypto.Hash import SHA
from Crypto.Cipher import PKCS1_v1_5 as Cipher_pkcs1_v1_5
from Crypto.Signature import PKCS1_v1_5 as Signature_pkcs1_v1_5
from Crypto.PublicKey import RSA
import base64

from thrift import Thrift
from thrift.transport import TSocket
from thrift.transport import TTransport
from thrift.protocol import TBinaryProtocol

from Common import constants
from Common import ttypes
from Credit import Credit

def str_req(req):
    return str(vars(req))

def gen_header():
    h = ttypes.Header()
    h.caller = 'loan-flow'
    h.traceId = 'tracetrace'
    h.spanId = 'spanspan'
    return h

def cal_sign(data):
    pem_file = open('loan-private.pem')
    pem = pem_file.read()
    rsakey = RSA.importKey(pem)
    signer = Signature_pkcs1_v1_5.new(rsakey)
    digest = SHA.new()
    digest.update(data)
    sign = signer.sign(digest)
    signature = base64.b64encode(sign)
    print signature
    return signature

def gen_sign(biz):
    si = ttypes.SignInfo()
    si.signMethod = 'RSA'
    si.signStr = cal_sign(biz)
    return si

def query_latest_credit_req():
    req = Credit.QueryLatestCreditReq()
    req.mid='1496998644570'
    req.uid='1496998644570'
    req.productId='2001'
    req.fundsChannelId='3003'
    return str_req(req)

def mapping_add_req():
    req = Credit.MappingAddReq('test-product', 'py-client-map-from', 'py-client-map-to-aaa')
    return str_req(req)

def mapping_get_req():
    req = Credit.MappingGetReq('test-product', 'py-client-map-from')
    return str_req(req)

if __name__ == '__main__':
    transport = TSocket.TSocket('127.0.0.1', 9201)
    transport = TTransport.TBufferedTransport(transport)
    protocol = TBinaryProtocol.TBinaryProtocol(transport)
    client = Credit.Client(protocol)
    transport.open()

    try:
        req = mapping_get_req()
        msg = client.getMapping(gen_header(), gen_sign(req), req)
        print str(msg)
    except:
        print 'traceback.format_e\n%s' % traceback.format_exc()

    print 'transport close'
    transport.close()
